/*
 * MIT License
 *
 * Copyright (c) 2019 Jianhui Zhao <zhaojh329@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef RTTY_RTTY_H
#define RTTY_RTTY_H

#include <stdbool.h>
#include <ev.h>

#include "buffer.h"
#include "file.h"
#include "list.h"

#define RTTY_MAX_TTY                5
#define RTTY_HEARTBEAT_INTEVAL      5.0

enum {
    MSG_TYPE_REGISTER = 0x00,
    MSG_TYPE_LOGIN = 0x01,
    MSG_TYPE_LOGOUT = 0x02,
    MSG_TYPE_TERMDATA = 0x03,
    MSG_TYPE_WINSIZE = 0x04,
    MSG_TYPE_CMD = 0x05,
    MSG_TYPE_HEARTBEAT = 0x06,
    MSG_TYPE_FILE = 0x07,
    MSG_TYPE_WEB = 0x08
};

struct rtty;

struct tty {
    pid_t pid;
    int pty;
    int sid;
    struct ev_io ior;
    struct ev_io iow;
    struct ev_child cw;
    struct buffer wb;
    struct rtty *rtty;
};

struct rtty {
    const char *host;
    int port;
    int sock;
    const char *devid;
    const char *token;        /* authorization token */
    const char *description;
    const char *username;
    bool ssl_on;
    const char *ssl_key;      /* path to device key */
    const char *ssl_cert;     /* path to device cert */
    struct buffer rb;
    struct buffer wb;
    struct ev_io iow;
    struct ev_io ior;
    struct ev_timer tmr;
    struct ev_loop *loop;
    int ninactive;
    ev_tstamp active;
    ev_tstamp last_heartbeat;
    bool reconnect;
    void *ssl;              /* Context wrap of openssl, wolfssl and mbedtls */
    struct tty *ttys[RTTY_MAX_TTY];
    struct file_context file_context;
    struct list_head web_reqs;
};

int rtty_start(struct rtty *rtty);
void rtty_exit(struct rtty *rtty);
void rtty_send_msg(struct rtty *rtty, int type, void *data, int len);

#endif
